<template>
  <div class="MSelect" @click="handleShowPop">
    <span v-if="selectValue?.[labelField]" class="MSelectValue">
      {{ selectValue?.[labelField] }}
    </span>
    <span v-else class="MSelectPlaceholder">{{ placeholder }}</span>
  </div>
</template>

<script lang="ts" setup>
  import {
    ref,
    withDefaults,
    defineEmits,
    defineProps,
    onMounted,
    watch,
  } from 'vue';
  import ModalSelect from './ModalSelect/index';

  interface Props {
    modelValue?: string | number;
    api: any;
    params?: any;
    options?: any[];
    valueField?: string;
    labelField?: string;
    resultField?: string;
    placeholder?: string;
  }
  const props = withDefaults(defineProps<Props>(), {
    valueField: 'value',
    labelField: 'label',
    resultField: 'data',
    placeholder: '请选择',
  });
  const emit = defineEmits(['update:modelValue', 'change']);

  const selectOptions = ref<any[]>([]);
  const selectValue = ref<any>({});

  const getOptions = () => {
    if (props.api) {
      const obj = props?.params || {};
      props.api(obj).then((res: any) => {
        selectOptions.value = res[props.resultField];
        getSelectItem();
      });
    } else {
      selectOptions.value = JSON.parse(JSON.stringify(props?.options || []));
      getSelectItem();
    }
  };

  const getSelectItem = () => {
    const item = selectOptions.value.find((t) => {
      return t[props.valueField] === props.modelValue;
    });

    selectValue.value = item || {};
  };

  watch(
    () => props.modelValue,
    () => {
      getSelectItem();
    },
    {
      immediate: true,
    }
  );

  watch(
    () => props.params,
    () => {
      if (props.api) {
        getOptions();
      }
    },
    { deep: true }
  );

  const handleShowPop = () => {
    ModalSelect({
      options: selectOptions.value,
      value: props.modelValue,
      valueField: props.valueField,
      labelField: props.labelField,
      placeholder: props.placeholder,
    }).then((res) => {
      const selectObj =
        selectOptions.value.find((t) => t[props.valueField] === res) || {};
      emit('update:modelValue', res);
      emit('change', res, selectObj);
    });
  };

  onMounted(() => {
    getOptions();
  });
</script>

<style lang="less" scoped>
  .MSelect {
    width: 100%;
    height: 100%;

    .MSelectPlaceholder {
      color: #c8c8c8;
    }
  }
</style>
